package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 静态资源工具类
 */
public class StaticResourceUtil {
    /**
     * 根据请求url返回资源的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        //获取当前编译后classes目录的绝对路径
        String classesPath = StaticResourceUtil.class.getResource("/").getPath();
        String result = classesPath.replaceAll("\\\\","/") + path;
        System.out.println("--------->"+result);
        return result;
    }

    /**
     * 将文件输入流输出
     * @param inputStream 文件输入流
     */
    public static void outputStaticResouce(InputStream inputStream, OutputStream outputStream) throws IOException {
        //先输出响应头
        int resourceSize = inputStream.available();//响应体长度
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //再输出响应体
        //读文件
        long written = 0;//已经读取的内容长度
        int byteSize = 1024;//计划缓存一次读取的长度
        byte[] bytes = new byte[byteSize];
        while (written<resourceSize){
            if(written+byteSize>resourceSize){//说明最后长度不足1024，就按真实的长度处理
                byteSize = (int) (resourceSize - written); //剩余最后的长度
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written+=byteSize;
        }
    }
}
